<template>
  <view class="batch-page">
    <!-- 顶部导航 -->
    <uni-nav-bar 
      title="批量操作" 
      left-icon="left" 
      :border="false"
      background-color="#fff"
      @clickLeft="handleBack"
    >
      <template #right>
        <text class="cancel-btn" @click="exitBatchMode">取消</text>
      </template>
    </uni-nav-bar>

    <!-- 批量操作工具栏 -->
    <view class="batch-toolbar">
      <view class="select-info">
        <text class="select-text">已选择 {{ selectedOrders.length }} 个订单</text>
        <text v-if="selectedOrders.length > 0" class="select-all-btn" @click="toggleSelectAll">
          {{ isAllSelected ? '取消全选' : '全选' }}
        </text>
      </view>
      
      <view class="batch-actions">
        <button 
          class="batch-btn confirm-btn" 
          :disabled="selectedOrders.length === 0"
          @click="showBatchStatusModal('confirmed')"
        >
          批量确认
        </button>
        <button 
          class="batch-btn complete-btn" 
          :disabled="selectedOrders.length === 0"
          @click="showBatchStatusModal('completed')"
        >
          批量完成
        </button>
        <button 
          class="batch-btn cancel-btn" 
          :disabled="selectedOrders.length === 0"
          @click="showBatchStatusModal('cancelled')"
        >
          批量取消
        </button>
        <button 
          class="batch-btn export-btn" 
          :disabled="selectedOrders.length === 0"
          @click="handleBatchExport"
        >
          导出订单
        </button>
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view
      scroll-y
      class="order-list-scroll"
      @refresherrefresh="handleRefresh"
      :refresher-triggered="isRefreshing"
      @scrolltolower="handleLoadMore"
    >
      <view v-if="orderList.length > 0" class="order-list">
        <view
          class="order-card"
          v-for="order in orderList"
          :key="order.id"
          :class="{ selected: selectedOrders.includes(order.id) }"
          @click="toggleOrderSelection(order.id)"
        >
          <!-- 选择框 -->
          <view class="select-checkbox">
            <uni-icons 
              :type="selectedOrders.includes(order.id) ? 'checkbox-filled' : 'checkbox'" 
              :color="selectedOrders.includes(order.id) ? 'var(--primary-color)' : '#999'"
              size="20"
            ></uni-icons>
          </view>

          <!-- 订单信息 -->
          <view class="order-info">
            <view class="card-header">
              <text class="order-no">订单号: {{ order.order_no }}</text>
              <uni-tag :text="getOrderStatus(order.status).text" :type="getOrderStatus(order.status).type" size="small" />
            </view>
            <view class="card-body">
              <view class="info-line">
                <text class="label">门店:</text> 
                <text class="value">{{ order.store?.name || 'N/A' }}</text>
              </view>
              <view class="info-line">
                <text class="label">场地:</text> 
                <text class="value">{{ order.venue?.name || 'N/A' }}</text>
              </view>
              <view class="info-line">
                <text class="label">会员:</text> 
                <text class="value">{{ order.member?.name || 'N/A' }}</text>
              </view>
            </view>
            <view class="card-footer">
              <text class="time">{{ formatTime(order.created_at) }}</text>
              <text class="amount">¥{{ (order.total_amount / 100).toFixed(2) }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <uni-load-more v-if="orderList.length > 0 || loading" :status="loadingStatus"></uni-load-more>
      
      <view v-if="orderList.length === 0 && !loading" class="empty-container">
        <uni-icons type="list" size="60" color="#999"></uni-icons>
        <text class="empty-text">暂无订单</text>
      </view>
    </scroll-view>

    <!-- 批量状态变更确认弹窗 -->
    <uni-popup ref="batchStatusPopup" type="dialog">
      <uni-popup-dialog 
        mode="input" 
        :title="`批量${batchActionText}`" 
        :placeholder="`请输入${batchActionText}备注(可选)`"
        @confirm="confirmBatchStatusChange"
        @close="batchStatusPopup.close()"
      >
        <template #default>
          <view class="batch-confirm-content">
            <text>确定要将选中的 {{ selectedOrders.length }} 个订单状态变更为'{{ batchActionText }}'吗？</text>
            <view class="selected-orders-preview">
              <text class="preview-title">选中的订单：</text>
              <view class="preview-list">
                <text 
                  v-for="order in selectedOrdersPreview" 
                  :key="order.id"
                  class="preview-item"
                >
                  {{ order.order_no }}
                </text>
              </view>
            </view>
          </view>
        </template>
      </uni-popup-dialog>
    </uni-popup>

    <!-- 导出进度弹窗 -->
    <uni-popup ref="exportProgressPopup" type="center">
      <view class="export-progress-modal">
        <view class="progress-header">
          <text class="progress-title">导出订单</text>
        </view>
        <view class="progress-content">
          <uni-icons type="download" size="40" color="var(--primary-color)"></uni-icons>
          <text class="progress-text">正在导出 {{ selectedOrders.length }} 个订单...</text>
          <view class="progress-bar">
            <view class="progress-fill" :style="{ width: exportProgress + '%' }"></view>
          </view>
          <text class="progress-percent">{{ exportProgress }}%</text>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { fetchOrders, batchUpdateOrderStatus, batchExportOrders } from '@/api/order';
import { fetchStores, fetchVenuesByStore } from '@/api/store';
import { fetchMembers } from '@/api/member';
import type { Order, OrderQuery } from '@/types/order';
import type { Store, Venue } from '@/types/store';
import type { Member } from '@/types/member';
import { OrderStatus } from '@/types/order';
import moment from 'moment';

// 订单数据
const orderList = ref<Order[]>([]);
const selectedOrders = ref<number[]>([]);
const queryParams = reactive<OrderQuery>({
  page: 1,
  pageSize: 20,
});

// 状态管理
const loading = ref(false);
const isRefreshing = ref(false);
const hasMore = ref(true);
const batchActionType = ref('');
const batchActionText = ref('');
const exportProgress = ref(0);

// 缓存数据
const storeCache = ref<Map<number, Store>>(new Map());
const venueCache = ref<Map<number, Venue>>(new Map());
const memberCache = ref<Map<number, Member>>(new Map());

// 引用
const batchStatusPopup = ref();
const exportProgressPopup = ref();

// 计算属性
const loadingStatus = computed(() => {
  if (loading.value) return 'loading';
  return hasMore.value ? 'more' : 'noMore';
});

const isAllSelected = computed(() => {
  return orderList.value.length > 0 && selectedOrders.value.length === orderList.value.length;
});

const selectedOrdersPreview = computed(() => {
  return orderList.value.filter(order => selectedOrders.value.includes(order.id)).slice(0, 5);
});

// 预加载关联数据
const preloadAllData = async () => {
  if (storeCache.value.size > 0) return;
  try {
    await Promise.all([
      fetchStores({ page: 1, pageSize: 500 }).then(res => res.list.forEach(s => storeCache.value.set(s.id, s))),
      fetchMembers({ page: 1, pageSize: 500 }).then(res => res.list.forEach(m => memberCache.value.set(m.id, m))),
    ]);
  } catch (error) {
    console.error('预加载数据失败:', error);
  }
};

// 获取订单列表
const getOrderList = async (isRefresh = false) => {
  if (loading.value) return;
  loading.value = true;

  if (isRefresh) {
    queryParams.page = 1;
  }

  try {
    const res = await fetchOrders(queryParams);
    const populatedOrders = res.list.map(order => ({
      ...order,
      store: storeCache.value.get(order.store_id),
      venue: venueCache.value.get(order.venue_id),
      member: memberCache.value.get(order.member_id),
    }));

    if (isRefresh) {
      orderList.value = populatedOrders;
      selectedOrders.value = []; // 刷新时清空选择
    } else {
      orderList.value = [...orderList.value, ...populatedOrders];
    }

    hasMore.value = orderList.value.length < res.total;
    
    if (queryParams.page) {
      queryParams.page++;
    } else {
      queryParams.page = 2;
    }

  } catch (error) {
    console.error('获取订单列表失败:', error);
    uni.showToast({ title: '获取订单列表失败', icon: 'none' });
  } finally {
    loading.value = false;
    isRefreshing.value = false;
  }
};

// 刷新处理
const handleRefresh = () => {
  isRefreshing.value = true;
  getOrderList(true);
};

// 加载更多
const handleLoadMore = () => {
  if (hasMore.value && !loading.value) {
    getOrderList();
  }
};

// 切换订单选择
const toggleOrderSelection = (orderId: number) => {
  const index = selectedOrders.value.indexOf(orderId);
  if (index > -1) {
    selectedOrders.value.splice(index, 1);
  } else {
    selectedOrders.value.push(orderId);
  }
};

// 切换全选
const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedOrders.value = [];
  } else {
    selectedOrders.value = orderList.value.map(order => order.id);
  }
};

// 显示批量状态变更弹窗
const showBatchStatusModal = (actionType: string) => {
  if (selectedOrders.value.length === 0) {
    uni.showToast({ title: '请先选择订单', icon: 'none' });
    return;
  }

  batchActionType.value = actionType;
  
  switch (actionType) {
    case 'confirmed':
      batchActionText.value = '确认';
      break;
    case 'completed':
      batchActionText.value = '完成';
      break;
    case 'cancelled':
      batchActionText.value = '取消';
      break;
  }

  batchStatusPopup.value.open();
};

// 确认批量状态变更
const confirmBatchStatusChange = async (remark: string) => {
  try {
    loading.value = true;
    
    let targetStatus: OrderStatus;
    switch (batchActionType.value) {
      case 'confirmed':
        targetStatus = OrderStatus.Confirmed;
        break;
      case 'completed':
        targetStatus = OrderStatus.Completed;
        break;
      case 'cancelled':
        targetStatus = OrderStatus.Cancelled;
        break;
      default:
        return;
    }

    // 批量更新订单状态
    const result = await batchUpdateOrderStatus(selectedOrders.value, targetStatus, remark);
    
    if (result.failed_count > 0) {
      uni.showToast({ 
        title: `成功${result.success_count}个，失败${result.failed_count}个`, 
        icon: 'none' 
      });
    } else {
      uni.showToast({ title: `批量${batchActionText.value}成功`, icon: 'success' });
    }
    
    // 刷新列表
    selectedOrders.value = [];
    handleRefresh();

  } catch (error: any) {
    console.error('批量操作失败:', error);
    uni.showToast({ 
      title: error.message || `批量${batchActionText.value}失败`, 
      icon: 'none' 
    });
  } finally {
    loading.value = false;
  }
};

// 批量导出订单
const handleBatchExport = async () => {
  if (selectedOrders.value.length === 0) {
    uni.showToast({ title: '请先选择订单', icon: 'none' });
    return;
  }

  try {
    exportProgressPopup.value.open();
    exportProgress.value = 0;

    // 模拟导出进度
    const progressInterval = setInterval(() => {
      exportProgress.value += 20;
    }, 300);

    // 调用批量导出API
    const result = await batchExportOrders(selectedOrders.value, 'excel');
    
    clearInterval(progressInterval);
    exportProgress.value = 100;
    
    setTimeout(() => {
      exportProgressPopup.value.close();
      
      // 下载文件
      uni.downloadFile({
        url: result.download_url,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.showToast({ title: '导出成功', icon: 'success' });
            
            // 保存到相册或分享
            uni.saveFile({
              tempFilePath: res.tempFilePath,
              success: () => {
                uni.showModal({
                  title: '导出成功',
                  content: '文件已保存，是否分享？',
                  success: (modalRes) => {
                    if (modalRes.confirm) {
                      uni.share({
                        provider: 'weixin',
                        type: 0,
                        href: result.download_url,
                        title: '订单导出文件',
                        summary: `导出了${selectedOrders.value.length}个订单`,
                      });
                    }
                  }
                });
              }
            });
          }
        },
        fail: () => {
          uni.showToast({ title: '下载失败', icon: 'none' });
        }
      });
      
    }, 500);

  } catch (error: any) {
    console.error('导出失败:', error);
    uni.showToast({ title: error.message || '导出失败', icon: 'none' });
    exportProgressPopup.value.close();
  }
};

// 退出批量模式
const exitBatchMode = () => {
  uni.navigateBack();
};

// 返回上一页
const handleBack = () => {
  uni.navigateBack();
};

// 获取订单状态
const getOrderStatus = (status: OrderStatus) => {
  const map: Record<OrderStatus, { text: string; type: 'success' | 'primary' | 'warning' | 'error' | 'info' }> = {
    [OrderStatus.Pending]: { text: '待处理', type: 'warning' },
    [OrderStatus.Confirmed]: { text: '已确认', type: 'primary' },
    [OrderStatus.Completed]: { text: '已完成', type: 'success' },
    [OrderStatus.Cancelled]: { text: '已取消', type: 'error' },
    [OrderStatus.Rescheduled]: { text: '已改签', type: 'info' },
  };
  return map[status] || { text: '未知', type: 'info' };
};

// 格式化时间
const formatTime = (timestamp: number) => {
  return moment(timestamp * 1000).format('YYYY-MM-DD HH:mm');
};

onLoad(async () => {
  await preloadAllData();
  handleRefresh();
});
</script>

<style lang="scss" scoped>
.batch-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--background-color);
}

.cancel-btn {
  color: var(--text-color-secondary);
  font-size: 14px;
}

.batch-toolbar {
  background-color: #fff;
  padding: 15px;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 44px;
  z-index: 10;

  .select-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    .select-text {
      font-size: 14px;
      color: var(--text-color);
    }

    .select-all-btn {
      font-size: 14px;
      color: var(--primary-color);
    }
  }

  .batch-actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;

    .batch-btn {
      flex: 1;
      min-width: 80px;
      height: 32px;
      border-radius: 16px;
      font-size: 12px;
      margin: 0;

      &[disabled] {
        opacity: 0.5;
      }

      &.confirm-btn {
        background-color: var(--primary-color);
        color: #fff;
      }

      &.complete-btn {
        background-color: #52c41a;
        color: #fff;
      }

      &.cancel-btn {
        background-color: var(--error-color);
        color: #fff;
      }

      &.export-btn {
        background-color: #fa8c16;
        color: #fff;
      }
    }
  }
}

.order-list-scroll {
  flex: 1;
  height: 0;
}

.order-list {
  padding: 10px;
}

.order-card {
  background-color: #fff;
  border-radius: var(--border-radius);
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: var(--shadow);
  display: flex;
  align-items: flex-start;
  gap: 15px;
  transition: all 0.2s;

  &.selected {
    border: 2px solid var(--primary-color);
    background-color: #f0f8ff;
  }

  .select-checkbox {
    padding-top: 2px;
  }

  .order-info {
    flex: 1;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 10px;
      border-bottom: 1px solid #f0f0f0;

      .order-no {
        font-size: 14px;
        font-weight: bold;
        color: var(--text-color);
      }
    }

    .card-body {
      padding: 10px 0;
      font-size: 14px;
      color: var(--text-color-secondary);
      
      .info-line {
        display: flex;
        margin-bottom: 5px;
        
        .label {
          width: 50px;
          flex-shrink: 0;
        }
        .value {
          color: var(--text-color);
        }
      }
    }

    .card-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 10px;
      border-top: 1px solid #f0f0f0;
      font-size: 12px;
      color: var(--text-color-placeholder);

      .amount {
        font-size: 16px;
        font-weight: bold;
        color: var(--error-color);
      }
    }
  }
}

.empty-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #999;
  padding-top: 100px;

  .empty-text {
    margin-top: 10px;
    font-size: 14px;
  }
}

.batch-confirm-content {
  padding: 20px 0;

  .selected-orders-preview {
    margin-top: 15px;
    padding: 10px;
    background-color: #f5f5f5;
    border-radius: 4px;

    .preview-title {
      font-size: 12px;
      color: var(--text-color-secondary);
      margin-bottom: 8px;
      display: block;
    }

    .preview-list {
      display: flex;
      flex-wrap: wrap;
      gap: 5px;

      .preview-item {
        font-size: 11px;
        color: var(--primary-color);
        background-color: #e6f7ff;
        padding: 2px 6px;
        border-radius: 2px;
      }
    }
  }
}

.export-progress-modal {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  width: 280px;

  .progress-header {
    text-align: center;
    margin-bottom: 20px;

    .progress-title {
      font-size: 16px;
      font-weight: bold;
      color: var(--text-color);
    }
  }

  .progress-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 15px;

    .progress-text {
      font-size: 14px;
      color: var(--text-color-secondary);
    }

    .progress-bar {
      width: 100%;
      height: 4px;
      background-color: #f0f0f0;
      border-radius: 2px;
      overflow: hidden;

      .progress-fill {
        height: 100%;
        background-color: var(--primary-color);
        transition: width 0.3s;
      }
    }

    .progress-percent {
      font-size: 12px;
      color: var(--text-color-secondary);
    }
  }
}
</style>